<template>
    <div class="materialMgt-index yuan-container">
        <a-card title="档案管理">
            <a-tabs type="card" :default-active-key="rawTypeKey" @change="tabChange">
                <a-tab-pane v-for="(item, i) in tabsData" :key="item.rawType" :tab="item.name"></a-tab-pane>
            </a-tabs>
            <div class="filter-panel">
                <a-input-search class="filter-list" allowClear v-model="keywords" placeholder="请输入品名/入库批号" @search="resetList" />
                <div class="filter-list" style="float: right;">
                    <a-button type="primary" @click="add" v-if="$utilCheckPermission(['materialManagementAdd'])">新增</a-button>
                    <a-button type="primary" @click="downloadTpl"
                        v-if="$utilCheckPermission(['materialManagementDownload'])">下载导入模板</a-button>
                    <a-upload name="file" :multiple="false" :beforeUpload="beforeUpload" :showUploadList="false"
                        v-if="$utilCheckPermission(['materialManagementImport'])">
                        <a-button type="primary" style="margin-left: 5px;">导入</a-button>
                    </a-upload>
                    <a-button type="primary" style="margin-left: 5px;" @click="exportData" v-if="$utilCheckPermission(['materialManagementExport'])">导出</a-button>
                </div>
            </div>
            <div class="table">
                <a-table bordered :rowKey="item=>item.id" :data-source="pageList" :columns="columns" :pagination="pagination"
                    :loading="loading">
                </a-table>
            </div>
        </a-card>
        <DetailVue :visible="detailVisible" @closeModal="() => detailVisible = false" :infoId="detailId" @resetList="getList" />
        <AddVue :visible="addVisible" @closeModal="() => addVisible = false" :infoId="editId" @resetList="getList" :rowKey="rawTypeKey"/>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { h } from "vue";
import nextApi, {MaterialListRes, ProductionListRes} from "@/api/nextApi";
import DetailVue from "./components/Detail.vue";
import AddVue from "./components/Add.vue";
import { downLoadFile } from "@/utils";
import config from "@/utils/config";
@Component({
    name: "materialMgtMgtIndex",
    components: { DetailVue, AddVue },
})
export default class extends Vue {
    tabsData = config.tabsData;
    pagination = {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    columns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center",
            customRender: (text: any, record: MaterialListRes, index: any) => `${index + 1}`,
        },
        {
            align: "center",
            dataIndex: "varietyName",
            key: "varietyName",
            title: "品名",
        },
        {
            align: "center",
            dataIndex: "productType",
            key: "productType",
            title: "物料类型",
            customRender: (text: any, record: MaterialListRes, index: any) => this.getRawTypeName(),
        },
        {
            align: "center",
            dataIndex: "materialCode",
            key: "materialCode",
            title: "物料代码",
        },
        {
            align: "center",
            dataIndex: "medicineClass",
            key: "medicineClass",
            title: "中药等级",
            customRender: (text: string, record: any, index: number) => `${record.medicineClass?record.medicineClass:'-'}`,
        },
        {
            align: "center",
            dataIndex: "productBigKind",
            key: "productBigKind",
            title: "产品大类",
        },
        {
            align: "center",
            dataIndex: "drugIdentificationCode",
            key: "drugIdentificationCode",
            title: "药品标识码",
        },
        {
            align: "center",
            dataIndex: "state",
            key: "state",
            title: "状态",
            customRender: (text: string, record: MaterialListRes, index: number) => {
                const stateBox = h(
                    "div",
                    { class: record.state === 0 ? "c-success" : "c-danger" },
                    record.state === 0 ? "启用" : "禁用"
                );
                return stateBox;
            },
        },
        {
            align: "center",
            dataIndex: "action",
            key: "action",
            title: "操作",
            width: 260,
            customRender: (text: any, record: MaterialListRes) => {
                const statusDom = h(
                    "a-popconfirm",
                    {
                        props: {
                            title: record.state === 0 ? "确定要禁用吗？" : "确定要启用吗？",
                            okText: "确定",
                            cancelText: "取消",
                        },
                        on: { confirm: () => this.clickDisable(record) },
                    },
                    [
                        h(
                            "a-button",
                            {
                                style: { marginRight: "5px" },
                                props: { icon: "tool", type: record.state === 0 ? "danger" : "primary", size: "small" },
                            },
                            record.state === 0 ? "禁用" : "启用"
                        ),
                    ]
                );

                const editBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "edit", type: "primary", size: "small" },
                        on: { click: () => this.editDetail(record) },
                    },
                    "编辑"
                );
                const detailBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "10px" },
                        props: { icon: "eye", type: "primary", size: "small" },
                        on: { click: () => this.showDetail(record) },
                    },
                    "详情"
                );

                const btn: any[] = [];
                if (this.$utilCheckPermission(['materialManagementCompile'])) btn.push(editBtn);
                if (this.$utilCheckPermission(['materialManagementDetails'])) btn.push(detailBtn);
                if (this.$utilCheckPermission(['materialManagementForbidden'])) btn.push(statusDom);
                return h("div", btn);
            },
        },
    ];
    loading = false;
    pageList: MaterialListRes[] = [];
    keywords = "";
    rawTypeKey = "中药材";
    async getList() {
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getMaterialList({
                pageSize: this.pagination.pageSize,
                pageNum: this.pagination.current,
                varietyName: this.keywords,
                productType: this.rawTypeKey,
                // state:0
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.rows || [];
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    tabChange(e: string) {
        this.rawTypeKey = e;
        this.resetList();
    }
    getRawTypeName() {
        const find = this.tabsData.find((item) => item.rawType === this.rawTypeKey);
        return find ? find.name : "--";
    }
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    async mounted() {
        this.getList();
    }
    detailId = "";
    detailVisible = false;
    showDetail(item: MaterialListRes) {
        this.detailId = item.id;
        this.detailVisible = true;
    }
    editId = "";
    addVisible = false;
    editDetail(item: MaterialListRes) {
        this.editId = item.id;
        this.addVisible = true;
    }
    add() {
        this.editId = "";
        this.addVisible = true;
    }

    async clickDisable(item: MaterialListRes) {
        try {
            this.loading = true;
            await nextApi.editMaterialState({
                id: item.id,
                state: item.state === 1 ? 0 : 1,
            });
        } finally {
            this.loading = false;
        }
        this.getList();
    }
    beforeUpload(file: any) {
        let formData = new FormData();
        formData.append("file", file);
        formData.append("type", this.rawTypeKey);
        this.uploadAccount(formData);
        return false;
    }
    async uploadAccount(formData: any) {
        this.loading = true;
        try {
            const res = await nextApi.uploadMaterial(formData);
            this.$message.success(res.msg);
            this.resetList();
        } finally {
            this.loading = false;
        }
    }
    downloadTpl() {
        this.loading = true;
        nextApi.downloadMaterialTpl({ type: this.getRawTypeName() }, (res: any) => {
            const blob = new Blob([res.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                // type: "application/vnd.ms-excel",
            });
            downLoadFile(blob, this.getRawTypeName() + "_导入模板");
            this.loading = false;
        });
    }
    // 导出档案数据
    exportData() {
        this.loading = true;
        nextApi.exportMaterialsData({ type: this.getRawTypeName() }, (res: any) => {
            const blob = new Blob([res.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                // type: "application/vnd.ms-excel",
            });
            downLoadFile(blob, this.getRawTypeName() + "_档案数据");
            this.loading = false;
        });
    }
}
</script>
<style lang="scss">
.materialMgt-index {
    padding: 20px;
}
</style>
